package com.ggb.smartstudy.service.Impl;

import com.ggb.smartstudy.entity.User;
import com.ggb.smartstudy.mapper.UserMapper;
import com.ggb.smartstudy.service.UserService;
import com.ggb.smartstudy.utils.ShaPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author gefangjie
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final ShaPasswordEncoder shaPasswordEncoder;


    public UserServiceImpl(UserMapper userMapper, ShaPasswordEncoder shaPasswordEncoder) {
        this.userMapper = userMapper;
        this.shaPasswordEncoder = shaPasswordEncoder;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public void createUser(User user) {
        // 检查用户名和邮箱是否已存在
        List<User> users = userMapper.getAllUsers();
        for (User existingUser : users) {
            if (existingUser.getUsername().equals(user.getUsername())) {
                throw new IllegalArgumentException("用户名已存在");
            }
            if (existingUser.getEmail().equals(user.getEmail())) {
                throw new IllegalArgumentException("电子邮箱已存在");
            }
        }
        // 加密用户密码
        user.setPassword(shaPasswordEncoder.encode(user.getPassword()));
        // 插入用户
        userMapper.insertUser(user);
    }

    @Override
    public void updateUser(User user) {
        // 如果用户传入了新的密码，对其进行加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(shaPasswordEncoder.encode(user.getPassword()));
        }
        userMapper.updateUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        // 删除用户
        return userMapper.deleteUser(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }
}
